CONTENTS | INDEX | PREV | NEXT
fwrite
NAME
fwrite - write data to a file pointer
SYNOPSIS
#include <stdio.h>
size_t robjs = fwrite(buf, objsize, nobjs, fp);
const void *buf;
size_t objsize;
size_t nobjs;
FILE *fp;
FUNCTION
fwrite() writes the specified number of objects to a file pointer
from the specified buffer and returns the actual number of objects
written or 0 or -1 depending on the error.
If the return value robjs is not equal to nobjs then a write error
occured.
Having two size arguments, an object size and number of objects,
simplifies the reading of structure arrays off disk.
NOTE
To use fwrite to read an arbitrary number of bytes one normally
uses the form: r = fwrite(buf, 1, n, fp); ... i.e. n objects
of size 1.
EXAMPLE
/*
* NOTE: run fread() example after this one to read data back
* from the file
*/
#include <stdio.h>
#define NOBJS 15
typedef struct {
short a, b, c, d;
} MyObj;
main()
{
FILE *fp;
MyObj O;
if (fp = fopen("T:fwrite_tmp", "wb")) {
short n;
for (n = 0; n < NOBJS; ++n) {
O.a = n;
O.b = n * 2;
O.c = n * 3;
O.d = n * 4;
if (fwrite(&O, sizeof(MyObj), 1, fp) != 1) {
puts("write error");
exit(1);
}
}
fclose(fp);
} else {
puts("Unable to create T:fwrite_tmp");
exit(1);
}
return(0);
}
INPUTS
void *buf; buffer to copy data from
size_t objsize; size of one object
size_t nobjs; number of objects to write
FILE *fp; file pointer to read objects from
RESULTS
size_t robjs; number of objects actually written (0 or EOF on error)
SEE ALSO
fread, fopen, fclose, fseek, ftell, rewind